package ne.aishuyuan.video.netty.client;

import io.netty.bootstrap.Bootstrap;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelFutureListener;
import io.netty.channel.ChannelOption;
import io.netty.channel.EventLoopGroup;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.nio.NioSocketChannel;
import lombok.Data;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicInteger;

@Slf4j
@Data
@Component
public class NettyClient {
    private static ChannelFuture future;
    private EventLoopGroup group;
    private Bootstrap bootstrap;
    private ScheduledExecutorService executorService = Executors.newScheduledThreadPool(1);
    private AtomicInteger reconnetTimes = new AtomicInteger(0);
    @Value("${netty.port}")
    private Integer port;
    @Value("${netty.server}")
    private String server;
    @Autowired
    private  NettyClientInitializer nettyClientInitializer;
    public void start() {
        group = new NioEventLoopGroup();
        bootstrap = new Bootstrap()
                .group(group)
                //该参数的作用就是禁止使用Nagle算法，使用于小数据即时传输
                .option(ChannelOption.TCP_NODELAY, true)
                .channel(NioSocketChannel.class)
                .option(ChannelOption.SO_KEEPALIVE,true)
                .option(ChannelOption.ALLOW_HALF_CLOSURE,true)
                .handler(nettyClientInitializer);
        try {
            createConnection();
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            group.shutdownGracefully();
            //　服务端挂了或者主动拒绝客户端的连接后，客户端不死心，每15秒重连试试，3次都不行就算了。修改下之前的客户端引导类（NettyClient，参见netty5心跳与业务消息分发实例），新增两个成员变量，在connect连接方法里的finally加入重连操作
            // 所有资源释放完成之后，清空资源，再次发起重连操作
            executorService.execute(new Runnable() {
                @Override
                public void run() {
                    // 重连3次均失败，关闭线程池
                    if (reconnetTimes.get() > 3) {
                        log.error("客户端重连3次失败");
                        executorService.shutdown();
                    }
                    // 每15秒重连一次
                    try {
                        TimeUnit.SECONDS.sleep(15);
                        try {
                            // 发起重连操作，连接成功后将阻塞
                            log.info(">>>>>>>>>>>>>>>连接失败，客户端重试开始");
                            start();
                        } catch (Exception e) {
                            reconnetTimes.getAndIncrement();
                            log.error("client try to reconnect failed, error : {}", e.getMessage());
                        }
                    } catch (InterruptedException e) {
                        reconnetTimes.incrementAndGet();
                        log.error("client try to reconnect failed, error : {}", e.getMessage());
                    }

                }
            });
        }
    }
    public void createConnection() throws Exception {
        future = bootstrap.connect(server, port).sync();

        future.addListener(new ChannelFutureListener() {
            @Override
            public void operationComplete(ChannelFuture channelFuture) throws Exception {
                log.info(">>>>>>>>>>>>>>>>>>>>客户端发送完毕");
            }
        });
        // 等待连接被关闭
        future.channel().closeFuture().sync();
    }
}